<template>
  <div class="home">
    <div class="header">
      <h3>TASK OA任务管理系统</h3>
      <el-button type="primary" @click="openDialog">新增任务</el-button>
    </div>
    <div class="tags">
      <el-tag 
        v-for="status in taskStatus" 
        style="cursor: pointer" 
        :key="status.value" 
        :type="filter === status.value?'primary':'info'"
        @click="setFilter(status.value)"
        >
        {{ status.label }}
      </el-tag>
    </div>
    <el-table style="width: 100%" :data="filteredTasks" v-loading="isLoading">
      <el-table-column prop="id" label="编号"></el-table-column>
      <el-table-column prop="description" label="任务描述"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template v-slot:default="{ row }">
          {{ row.status === 1 ? `未完成` : `已完成` }}
        </template>
      </el-table-column>
      <el-table-column prop="expected_completion_time" label="预期完成时间"></el-table-column>
      <el-table-column prop="actual_completion_time" label="实际完成时间"></el-table-column>
      <el-table-column fixed="right" label="操作" width="100px">
        <template #default="{row:task}">
          <el-popconfirm title="确定要删除吗?" @confirm="deleteTask(task.id)">
            <template v-slot:reference>
              <el-link type="danger">删除</el-link>
            </template>
          </el-popconfirm>
          <el-popconfirm title="确定要完成吗?" @confirm="completeTask(task.id)">
            <el-link slot="reference" type="success">完成</el-link>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="新增任务" width="50%" :visible.sync="dialogVisible">
      <el-form :model="taskForm" ref="taskForm" :rules="taskRules">
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="taskForm.description" type="textarea" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="预计完成时间" prop="expected_completion_time">
          <el-date-picker v-model="taskForm.expected_completion_time" type="datetime"
            placeholder="请选择预计完成时间"></el-date-picker>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleNewTask">确定</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent } from "vue";
import {mapState,mapGetters,mapActions, mapMutations} from 'vuex';
export default defineComponent({
  name: "HomeView",
  data: () => ({
    taskStatus: [//因为此状态只在当前组件使用
      { label: "全部", value: "all" },
      { label: "未完成", value: 1 },
      { label: "已完成", value: 2 },
    ],
    dialogVisible: false,//表示新增任务对话框是否显示
    taskForm: {
      description: '',
      expected_completion_time: ''
    },
    taskRules: {
      description: [//当输入框失去焦点的时候进行必填项验证，如果没有输入任何内容的话就提示错误信息
        { required: true, message: '请输入任务名称', trigger: 'blur' },
        { min: 5, max: 200, message: '输入长度应该是5到200个字符之间', trigger: 'blur' }
      ],
      expected_completion_time: [
        { required: true, message: '请输入预计任务完成时间', trigger: 'blur' },
      ]
    }
  }),
  computed:{
    //把仓库中task模块中的状态全部映射为当前Vue组件实例的计算属性
    ...mapState('task',['tasks','filter','isLoading']),
    //把仓库中的task模块中的getters映射为当前Vue组件的实例的计算属性
    ...mapGetters('task',['filteredTasks'])
  },
  created(){
    //调用接口获取所有的任务
    this.retrieveTasks();
  },
  methods: {
    ...mapActions('task',['retrieveTasks','createTask','deleteTask','completeTask']),
    ...mapMutations('task',['setFilter']),
    openDialog() {//让新增加任务对话框显示
      this.dialogVisible = true;
    },//处理增加任务
    handleNewTask() {
      //1.校验用户的输入是否合法
      //2.获取用户输入的数据
      //3.调用远程后台接口添加任务
      // this.$refs.taskForm 可以获取el-form组件的实例，组件实例本质就是Vue实例,上面也可以定义方法
      this.$refs.taskForm.validate(async (valid) => {
        //如果用户校验成功，说明信息输入合法
        if (valid) {
          const { description, expected_completion_time } = this.taskForm;
          const formatted_expected_completion_time = expected_completion_time.toLocaleString(
            'zh-CN', { hour12: false } //把预计完成时间转化为一个24小时制的中文的时间
          );
          try {
            const payload = {description,expected_completion_time:formatted_expected_completion_time};
            //如果没有mapActions的话，需要通过仓库派发一个动作，动作类型还要携带命名空间的前缀，还要传递payload数据
            //await this.$store.dispatch('task/createTask',payload);
            //如果已经映射过一，则可以直接创建
            await this.createTask(payload);
            //关闭新增窗口
            this.dialogVisible = false;
            //让表单里面的字段一切都恢复到最初的状态
            this.$refs.taskForm.resetFields();
            this.$message.success('任务创建成功');
          } catch (error) {
            this.$message.error('任务创建失败');
          }
        } else {
          this.$message({
            type: 'error',
            message: '表单验证失败'
          });
        }
      });
    }
  }
});
</script>
<style lang="less" scoped>
.home {
  width: 80%;
  margin: 0px auto;

  .header {
    display: flex;
    justify-content: space-around;
    align-items: center;
    border-bottom: 1px solid #ccc;
  }

  .tags {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;

    span {
      margin: 10px;
    }
  }

  ::v-deep(.el-link) {
    margin-left: 5px;
  }

  ::v-deep(.el-dialog__header) {
    text-align: left;
  }

  ::v-deep(.el-form-item__content) {
    text-align: left;
  }
}
</style>
